package com.asa.renderer;

import org.lwjgl.BufferUtils;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.stb.STBImage.stbi_image_free;
import static org.lwjgl.stb.STBImage.stbi_load;

public class Texture {

    private String filepath;
    private int textID;


    public Texture(String filepath){
        this.filepath = filepath;

        //生成GPU纹理
        textID = glGenTextures();

        glBindTexture(GL_TEXTURE_2D,textID);

        //设置纹理参数
        //设置图片在双向上重复显示
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

        //像素化
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);

        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);

        IntBuffer width = BufferUtils.createIntBuffer(1);
        IntBuffer height = BufferUtils.createIntBuffer(1);
        IntBuffer channels = BufferUtils.createIntBuffer(1);
        ByteBuffer image = stbi_load(filepath,width,height,channels,0);

        if (image != null){
            if (channels.get(0)==3){
                glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width.get(0),height.get(0),0,
                        GL_RGB,GL_UNSIGNED_BYTE,image);
            }else if (channels.get(0)==4){
                glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width.get(0),height.get(0),0,
                        GL_RGBA,GL_UNSIGNED_BYTE,image);
            }else {
                assert false : "Error:Texture 通道数未知 '"+filepath+" '";

            }

        }else{
            assert false : "Error:Texture 无法加载图像 '"+filepath+" '";
        }

        stbi_image_free(image);


    }

    public void bind(){
        glBindTexture(GL_TEXTURE_2D,textID);
    }


    public void unbind(){
        glBindTexture(GL_TEXTURE_2D,0);
    }



}
